package gr.atc.epart;


import gr.atc.epart.SurveyQuestion.QuestionType;
import gr.atc.epart.actions.Survey;
import gr.atc.epart.googlewrapper.GoogleServiceCallbackType;
import gr.atc.epart.googlewrapper.accounts.GoogleAccountManager;
import gr.atc.epart.googlewrapper.accounts.GoogleLoginDialog;
import gr.atc.epart.googlewrapper.moderator.GoogleModerator;
import gr.atc.epart.googlewrapper.moderator.ModeratorSeries;
import gr.atc.epart.googlewrapper.moderator.ModeratorTopic;
import gr.atc.epart.googlewrapper.moderator.ModeratorVote;

import java.util.ArrayList;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.Toast;

public class SurveyQuestionsCreationActivity extends Activity  
{

	private static final int DIALOG_LOGIN_INPUT= 0;
	private static final int DIALOG_LOGIN_FAILED = 1;
	
	private static final int SHOW_WIZARD_MAIN_SCREEN= 0;
	private static final int SHOW_WIZARD_YESNO_SCREEN = 1;
	private static final int SHOW_WIZARD_MULTIPLECHOICE_SCREEN = 2;
	private static final int SHOW_WIZARD_MULTIPLESELECTION_SCREEN = 3;
	
	
	private GoogleModerator _moderator;
	int _moderatorSeriesId;

	ModeratorSeries _series;
	

	ProgressDialog _progressDialog;

	ModeratorTopic _selectedTopic;
	GoogleAccountManager _accountManager;
	
	private int _currentQuestionIndex;
	private SurveyQuestion.QuestionType _currentQuestionType;
	private String _sumbissionText;
	
	
	
	 private class OnGoogleLoginDialogHandler implements GoogleLoginDialog.OnCompleteListener
	 {

		@Override
		public void cancel()
		{
			// return to the previous activity.
			SurveyQuestionsCreationActivity.this.finish();
		}

		@Override
		public void login(String username, String password)
		{
			 showProgressDialog();
			_moderator.authenticate(username,password);
		}
	 }
	 
	 //
	 // used to receive callbacks   
	 //
	 private Handler _messageHandler = new Handler() 
	  {
	      public void handleMessage(Message msg) 
	      {  
	          switch(msg.what) 
	          {
	        	  
	        	  case GoogleServiceCallbackType.UserAuthenticationRequired:
	        	  	  {
	        	  		// display a dialog to receive the password....the username is known..!
	        	  		 
	        	  		 String username = _accountManager.getAccountEmail();
	        	  		
	        	  		 GoogleLoginDialog logindialog = new GoogleLoginDialog(SurveyQuestionsCreationActivity.this,"Please login into Google Moderator",username,new OnGoogleLoginDialogHandler());
	        	  		 logindialog.show();
	        		  
	        	  	  }
	        		  break;
	        		
	        	  case GoogleServiceCallbackType.ModeratorServiceIsReady:

	        		  _moderator.getSeries(_moderatorSeriesId);
	        		  //_currentQuestionIndex = 0;
	        		  //_wizardDialogHandler.sendEmptyMessage(SHOW_WIZARD_MAIN_SCREEN);
	        			
	        		break;
	        		  
	        	  case GoogleServiceCallbackType.ModeratorSeriesReceived:
	        		  
	        		  // stop the progress dialog
	        		  dismissProgessDialog();

	        		  ArrayList<ModeratorSeries> seriesList = (ArrayList<ModeratorSeries>) msg.getData().getSerializable("SERIES");
	        		  
	        		  if (seriesList == null)
	        		  {
	        			  // error...cannot retrieve series
	        			  this.sendEmptyMessage(GoogleServiceCallbackType.OperationError);
	        		  }
	        		  else
	        		  {
		        		  // the list is used for future use...in order to retrieve more than one series at a time
		        		  // at the moment only one series is contained
		        		  _series = seriesList.get(0);
		        		  
		        		  if (_series != null)
		        		  {
		        			  _currentQuestionIndex = _series.getNumOfTopics() + 1;
		        			  _wizardDialogHandler.sendEmptyMessage(SHOW_WIZARD_MAIN_SCREEN);
		        		  }
	        			  else
	        			  {
	        				  this.sendEmptyMessage(GoogleServiceCallbackType.OperationError);
	        			  }
	        		  }

	        		  break;

	        	  case GoogleServiceCallbackType.ModeratorNewTopicAdded:
	        		  
	        		  // the question entry is created
	        		  // depending on the question type created
	        		  // we need to add as submision the options (in case of multiple choice/multiple selection) 
	        		  // or the question text
	        		  ArrayList<ModeratorTopic> topics = (ArrayList<ModeratorTopic>) msg.getData().getSerializable("TOPIC");

	        		  //TODO:: at the moment ONLY the yes/no type question is supported
	        		   if (_currentQuestionType == QuestionType.YesNo)
	        		   {
	        			   // add the same description as a submision
	   			  			String username = AccountUtil.getAccountName(SurveyQuestionsCreationActivity.this.getBaseContext());
	        			   _moderator.addSubmision(topics.get(0),username,_sumbissionText,null,null);	        			   
	        		   }
	        		  
	        		  break;

	        	  case GoogleServiceCallbackType.ModeratorSubmissionAdded:
	        		  // stop the progress dialog
	        		  dismissProgessDialog();
	        		  
	  				  Toast.makeText(getBaseContext(), "Question added.", Toast.LENGTH_LONG).show();
	        		  
	        		  //
	        		  //we should now return to the wizard main screen
	        		  //  TODO:: when multiple choice/selection question support is added, we need to see this again
	        		  // because it will have to submit more than one submission
	        		  
	        		  _wizardDialogHandler.sendEmptyMessage(SHOW_WIZARD_MAIN_SCREEN);
	        		  
	        		  break;
	        		  
	        	  case GoogleServiceCallbackType.OperationError:
	        	  	{
	        	  		if (msg.getData()!=null)
	        	  		{
		        	  		String error = msg.getData().getString("DESCRIPTION");
		        	  		showErrorAlert("Google moderator error:"+error);
		        	  		
	        	  		}
	        	  		dismissProgessDialog();
	        	  	}
	        		  break;
	          }
	      }
	  };
	

	@Override
	public void onCreate(Bundle icicle) 
	{
		super.onCreate(icicle);
		_accountManager = new GoogleAccountManager(this);
		
		//
		// keep track on which series we are working on
		//
		Survey selectedSurvey = (Survey)EPartVolatileDataStore.getInstance().getSelectedAction();
		_moderatorSeriesId = selectedSurvey.getModeratorSeriesId();

		//_currentQuestionIndex = 0;
		//displayWizardFirstPage();
		//
		// start google moderator
		//
		try
		{
			_moderator = new GoogleModerator(_messageHandler);
			//
			// try to authenticate (IF there are previous credentials present)
			//
			_moderator.authenticate();
		
		}catch (Exception e )
		{
			
		}
		
	}

	
	final Handler _wizardDialogHandler = new Handler() 
	{
		public void handleMessage(Message msg) 
		{
			switch (msg.what)
			{
				case SHOW_WIZARD_MAIN_SCREEN:
	        		displayWizardFirstPage();
					break;
				case SHOW_WIZARD_YESNO_SCREEN:
					displayWizardYesNoEntryQuestionPage();
					break;
				case SHOW_WIZARD_MULTIPLECHOICE_SCREEN:
					break;
				case SHOW_WIZARD_MULTIPLESELECTION_SCREEN:
					break;
			}
		}
	};

	
	private void displayWizardFirstPage()
	{
		
		setContentView(R.layout.newsurveyquestionwizpage1);

		// this will display the first page of the wizard (select typwe of question)
		// set a click listener on the next button in order to get the type of question required
		// set a click listener on the finish button in order to terminate the wizard 

		
		OnClickListener nextButtonListener = new OnClickListener() 
		   {
			  	public void onClick(View v) 
			  	{
			  		
			  		RadioButton rbYesno = (RadioButton)findViewById(R.id.surveyquestiontype_yesno);
			  		
			  		if (rbYesno.isChecked())
			  		{
			  			_wizardDialogHandler.sendEmptyMessage(SHOW_WIZARD_YESNO_SCREEN);
			  		}
			  		
			  		/*
			  		RadioButton rbYesno = (RadioButton)findViewById(R.id.surveyquestiontype_yesno);
			  		RadioButton rbMultipleChoice = (RadioButton)findViewById(R.id.surveyquestiontype_multiplechoice);
			  		RadioButton rbMultipleSelection = (RadioButton)findViewById(R.id.surveyquestiontype_multipleselection);
			  		
			  		if (rbYesno.isChecked())
			  		{
			  			_wizardDialogHandler.sendEmptyMessage(SHOW_WIZARD_YESNO_SCREEN);
			  		}
			  		else if (rbMultipleChoice.isChecked())
			  		{
			  			
			  		}
			  		else if (rbMultipleSelection.isChecked())
			  		{
			  			
			  		}
			  		*/
			  	}

		   };
		
		
		Button nextButton = (Button)findViewById(R.id.surveyquestiontype_NextButton);
		nextButton.setOnClickListener(nextButtonListener);
		
		
		OnClickListener finishButtonListener = new OnClickListener() 
		   {
			  	public void onClick(View v) 
			  	{
			  		finish();
			  	}
		   };

		Button finishButton = (Button)findViewById(R.id.surveyquestiontype_FinishButton);
		finishButton.setOnClickListener(finishButtonListener);
		 
	}

	private void displayWizardYesNoEntryQuestionPage()
	{
		
		SurveyQuestionsCreationActivity.this.setContentView(R.layout.newsurveyquestionwizpage_yesno);
		
		// this will display the page to enter a simple yes/no question 
		// set a click listener on the next button in order to add the question and proceed
	
		OnClickListener addButtonListener = new OnClickListener() 
		   {
			  	public void onClick(View v) 
			  	{
			  		// a simple yes no question is created as follows
			  		// a new topic is created with a title starting from "%" followed by a not important name
			  		// the topic's description is set to the question text
			  		// and then a submission with the same description is added
			  		// (this is a two phase asynchronous procedure)

			  		showProgressDialog();
			  		
			  		_currentQuestionType = QuestionType.YesNo;
			  		
			  		String username = AccountUtil.getAccountName(SurveyQuestionsCreationActivity.this.getBaseContext());
			  		
			  		EditText questionText = (EditText)findViewById(R.id.surveyquestiontype_yes_no_questiontext);
			  		_sumbissionText = questionText.getText().toString();
			  		// submit topic....and when this is done...add a similar submision
			  		_moderator.addTopic(_moderatorSeriesId, createTopicName(QuestionType.YesNo),_sumbissionText , username);
			  		
			  	}

		   };
		   
		Button addButton = (Button)findViewById(R.id.surveyquestiontype_yes_no_AddButton);
		addButton.setOnClickListener(addButtonListener);

	}

	
	public void onClick(View v) 
  	{
		
		RadioButton rbYesno = (RadioButton)findViewById(R.id.surveyquestiontype_yesno);
  		if (rbYesno.isChecked())
  		{
  			displayWizardYesNoEntryQuestionPage();
  		}
		
  		/*
  		RadioButton rbYesno = (RadioButton)findViewById(R.id.surveyquestiontype_yesno);
  		RadioButton rbMultipleChoice = (RadioButton)findViewById(R.id.surveyquestiontype_multiplechoice);
  		RadioButton rbMultipleSelection = (RadioButton)findViewById(R.id.surveyquestiontype_multipleselection);
  		
  		if (rbYesno.isChecked())
  		{
  			displayWizardYesNoEntryQuestionPage();
  		}
  		else if (rbMultipleChoice.isChecked())
  		{
  			
  		}
  		else if (rbMultipleSelection.isChecked())
  		{
  			
  		}
  		*/
  	}
	protected String createTopicName(QuestionType questionType)
	{
		// depending on the type of the question, an incremental name is returned
		String questionTypeIndicator="";
		
		if (questionType == QuestionType.YesNo)
			questionTypeIndicator="%";
		else if (questionType == QuestionType.MultipleChoice)
			questionTypeIndicator="#";
		else if (questionType == QuestionType.MultipleSelect)
			questionTypeIndicator="$";

		return String.format("%sQUESTION_%04d", questionTypeIndicator,_currentQuestionIndex);
		
	}


	private void showProgressDialog() {
		
		_progressDialog = new ProgressDialog(this);
		_progressDialog.setMessage("Please wait...");
		_progressDialog.setIndeterminate(true);
		_progressDialog.setCancelable(false);
		_progressDialog.show();
	}

	public void showErrorAlert(String msg) {

		AlertDialog.Builder dlgAlert = new AlertDialog.Builder(this);
		dlgAlert.setMessage(msg);
		dlgAlert.setTitle("Error");
		dlgAlert.setPositiveButton("OK", null);
		dlgAlert.setCancelable(true);
		dlgAlert.create();
		dlgAlert.show();
	}
	
	private void dismissProgessDialog()
	{
		_progressDialogHandler.sendEmptyMessage(0);
	}

	   // Define the Handler that receives messages from the thread and update the progress
	final Handler _progressDialogHandler = new Handler() 
	{
		public void handleMessage(Message msg) 
		{
			if (_progressDialog!=null)
				_progressDialog.dismiss();
		}
	};
	

}
